import React, { useState, useRef, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Link, useNavigate } from 'react-router-dom';

import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Progress } from '@/components/ui/progress';
import MessageAlert from '@/components/ui/MessageAlert';
import { MembershipSelector } from '@/components/MembershipSelector';
import { AG_ID, CDN_BASE_URL, API_ENDPOINTS } from '@/config';
import apiService, { UploadFileInfoRequest, Media, OssUploadSignatureResponse } from '@/services/apiService';
import { message } from 'antd';
import { useLocation } from 'react-router-dom';


import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  rectSortingStrategy,
} from '@dnd-kit/sortable';
import {
  useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';

interface ImageDimensions {
  width: number;
  height: number;
}

// Media 和 UploadResponse 接口已移动到 apiService 中

const Publish: React.FC = () => {
  const [id, setId] = useState('0');
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const [coverImage, setCoverImage] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [price, setPrice] = useState(0);
  const [isPublic, setIsPublic] = useState(false);
  const [visibility, setVisibility] = useState('private'); // 新增可见性状态
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [mediaItems, setMediaItems] = useState<{
    file?: File;
    preview: string;
    url: string;
    id?: string;
    type: string;
    size: number;
    width?: number;
    height?: number;
    deleted?: boolean;
  }[]>([]);
  const [charCount, setCharCount] = useState(0);
  const [thumbnail_url, setThumbnail_url] = useState('');
  const maxChars = 1000;
  const [showPriceInput, setShowPriceInput] = useState(false);
  const [selectedMembershipTiers, setSelectedMembershipTiers] = useState<string[]>([]);
  const [membershipTiers, setMembershipTiers] = useState<any[]>([]);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [mediaType, setMediaType] = useState(1);
  const [ossConfig, setOssConfig] = useState<OssUploadSignatureResponse | null>(null);
  const [filesArray, setFilesArray] = useState<File[]>([]);
  const [isUploading, setIsUploading] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [sendMessage, setSendMessage] = useState('');
  const location = useLocation();
  const { item, originalPost } = location.state || {};
    const navigate = useNavigate();

  // 当originalPost存在时，填充表单数据
  useEffect(() => {
    console.log('originalPost:', originalPost);
    if (originalPost) {
      setId(originalPost.id)
      setTitle(originalPost.title || '');
      setBody(originalPost.body || '');
      setPrice(originalPost.price || 0);
      setIsPublic(originalPost.free === 1);
      setVisibility(originalPost.free === 1 ? 'public' : originalPost.price > 0 ? 'Purchase' : 'private');
      setThumbnail_url(originalPost.thumbnailUrl || '');
      
      // 如果有媒体文件，转换为统一的mediaItems格式
      if (originalPost.medias && originalPost.medias.length > 0) {
        const convertedMedias = originalPost.medias.map((media: Media) => ({
          preview: media.url,
          url: media.url,
          id: media.id,
          type: media.type,
          size: media.size,
          width: media.width,
          height: media.height,
          deleted: false
        }));
        console.log('转换后的媒体文件:', convertedMedias);
        setMediaItems(convertedMedias);
      }
      setIsEdit(true);
    }
  }, [originalPost]);
  
  // 页面载入完成后获取支付方案数据
  useEffect(() => {
    const fetchMembershipTiers = async () => {
      try {
        const result = await apiService.getSubscriptionPlans({
          agId: AG_ID,
          offset: "0",
          limit: "10",
        });
        if (result && result.data) {
          console.log('获取会员等级成功:', result);
          setMembershipTiers(result.data.rows || result.data || []);
          setSelectedMembershipTiers( result.data.rows.map((row: any) => row.id));
        }
      } catch (error) {
        console.error('获取会员等级失败:', error);
      }
    };
    
    fetchMembershipTiers();
  }, []);

  // 页面加载后获取OSS配置
  useEffect(() => {
    const fetchOssConfig = async () => {
      try {
        const config = await apiService.getOssUploadSignature();
        if (config) {
          console.log('OSS配置获取成功:', config);
          setOssConfig(config);
        } else {
          console.warn('OSS配置获取失败');
        }
      } catch (error) {
        console.error('获取OSS配置失败:', error);
      }
    };
    
    fetchOssConfig();
  }, []);

  useEffect(() => {
    setShowPriceInput(visibility === 'Purchase');
    if (visibility !== 'Purchase') {
      setPrice(0);
    }
  }, [visibility]);
  useEffect(() => {
    setCharCount(body.length);
  }, [body]);

  // 监听可见性变化，同步更新 isPublic 状态
  useEffect(() => {
    setIsPublic(visibility === 'public');
  }, [visibility]);

  // 处理会员等级选择变化
  const handleMembershipSelectionChange = (selectedTiers: string[]) => {
    console.log('Selected membership tiers:', selectedTiers);
    setSelectedMembershipTiers(selectedTiers);
    const selectedString = selectedTiers.join(',');
    console.log('Selected membership tiers as string:', selectedString);
  };
  
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    // TODO: 实现发布逻辑
    // API_ENDPOINTS.POST_NEW_POST
    console.log({ title, body, coverImage, price, isPublic, mediaItems, selectedMembershipTiers });
    const access_token = localStorage.getItem('access_token');
    if (!access_token) {
      alert('请先登录');
      return;
    }
    var free = 0;
    var selectedString = "0";
    console.log('selectedString:', selectedString);
    if (visibility == 'Paid') {
      selectedString = selectedMembershipTiers.join(',');
    }
    if (visibility == 'public') {
      free = 1;
    }
    if (visibility == 'private') {
      setSelectedMembershipTiers( membershipTiers.map((row: any) => row.id));
      selectedString = selectedMembershipTiers.join(',');
    }
    if (visibility == 'Purchase') {
      
      if(price <= 0) {
        setSendMessage('价格必须大于0');
        return;
      }
    }
    if(mediaItems.length == 0) {
      setSendMessage('请选择上传图片');
      return;
    }
    if(title.length == 0) {
      setSendMessage('请输入标题');
      return;
    }
    console.log('更新后的mediaItems:', mediaItems);
    // 分别处理未删除和已删除的媒体项
    const activeMedias = mediaItems.filter(item => item.id && !item.deleted).map((item, index) => ({
      id: item.id!,
      postId: "-1",
      url: item.url,
      type: item.type,
      size: item.size,
      width: item.width || 0,
      height: item.height || 0,
      sort: index,
    }));
    
    const cover = activeMedias[0].url
    // 获取被删除的媒体项ID列表
    const deletedMediaIds = mediaItems.filter(item => item.id && item.deleted).map(item => item.id!);
    console.log('被删除的媒体ID:', deletedMediaIds);
    try {
      const post = {
        id,
        title,
        body,
        price,
        isPublic,
        thumbnailUrl:cover,
        blogName: 'bn',
        visibility,
        agId: AG_ID,
        mediaType: mediaType,
        nodeName: 'timeline',
        groupId: selectedString,
        free: free,
      }
      const url = isEdit ? API_ENDPOINTS.POST_EDIT_POST : API_ENDPOINTS.POST_NEW_POST;
      const result = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${access_token}`,
        },
        body: JSON.stringify({
          post : post,
          medias: activeMedias,
          deletedMediaIds: deletedMediaIds,
          gids: selectedMembershipTiers,
        }),
      });

      if (result.ok) {
        // alert('Post published successfully!');
        // Optionally, redirect or clear form
        const data = await result.json();
        if (data.code === "1" && data.flag === "1") {
          message.success(data.msg || "");
          setSendMessage("发布成功");
          // setTimeout(() => {
          //   navigate("/");
          // }, 1000);
        } else {
          message.error(data.msg || "发生错误");
          setSendMessage(data.msg || "发生错误");
        }
      } else {
        message.error("创建新贴文时，发生错误");
        setSendMessage("创建新贴文时，发生错误");
      }
    } catch (error) {
      console.error('Error publishing post:', error);
      setSendMessage('发布时发生错误，请重试');
      message.error('发布时发生错误，请重试');
    }
  };

  const handleFileUpload = async (file: File, ossConfig: OssUploadSignatureResponse) => {
    const fileName = await apiService.uploadFileToOss(
      file, 
      ossConfig, 
      (progress) => {
        setUploadProgress(progress);
        console.log(`上传进度: ${progress}%`);
      }
    );
    
    if (fileName) {
      console.log('文件上传成功:', fileName);
      setUploadProgress(100);
    }
    return fileName;
  };

  const getImageDimensions = (file: File): Promise<{width: number, height: number}> => {
    return new Promise((resolve) => {
        const img = new Image();
        img.onload = () => {
            resolve({width: img.width, height: img.height});
        };
        img.src = URL.createObjectURL(file);
    });
};

  const uploadFileInfo = async (file: File, fileName?: string) => {
    const dimensions = await getImageDimensions(file);
    var selectedString = "0";
    console.log('selectedString:', visibility);
    if (visibility == 'Paid') {
      selectedString = selectedMembershipTiers.join(',');
    }

    const uploadData: UploadFileInfoRequest = {
      url: fileName || '',
      outUrl: fileName || '',
      mediaType: 1,
      type: file.type,
      size: file.size,
      lastModified: file.lastModified,
      width: dimensions.width,
      height: dimensions.height,
      agId: AG_ID,
      postId: "-1",
      groud_id: selectedString
    };

    const result = await apiService.uploadFileInfo(uploadData);
    if (!result) {
      console.error('上传文件信息失败: 没有返回结果');
      return null;
    }

    if (result.code === 1 && result.data) {
      setThumbnail_url(result.data.url);
      // 更新对应的mediaItem，添加服务器返回的信息
      console.log('更新mediaItem:', result.data);
      console.log('mediaItems:', mediaItems);
      const media = result.data;

      const convertedMedias = {
        preview: media.url,
        url: media.url,
        id: media.id,
        type: media.type,
        size: media.size,
        width: media.width,
        height: media.height,
        deleted: false
      };
      return convertedMedias;
    } else {
      console.error('上传文件信息失败:', result);
      return null;
    }
  };
  const handleImageClick = () => {
    fileInputRef.current?.click();
  };

  const handleMultiImageChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && !isUploading) {
      // 将新选择的文件转换为数组并与现有文件合并
      const newFilesArray = Array.from(e.target.files);
      const combinedFilesArray = [...filesArray, ...newFilesArray];
      setFilesArray(combinedFilesArray); // 更新state
      
      setIsUploading(true); // 开始上传，禁止添加新文件
      
      try {
        console.log('多图上传OSS配置:', ossConfig);
        
        // 使用预先获取的OSS配置或重新获取
        let currentOssConfig = ossConfig;
        if (!currentOssConfig) {
          currentOssConfig = await apiService.getOssUploadSignature();
          if (!currentOssConfig) {
            alert('获取上传配置失败，请稍后再试');
            setIsUploading(false);
            return;
          }
          setOssConfig(currentOssConfig);
        }
        
        // 顺序处理每个文件
        const newImages: Array<{ file: File; preview: string; url: string; type:string, id:string; size:number, width:number, height:number , deleted:boolean }> = [];


        
        for (let i = 0; i < newFilesArray.length; i++) {
          const file = newFilesArray[i];
          
          // 创建预览
          const reader = new FileReader();
          const preview = await new Promise<string>((resolve) => {
            reader.onloadend = () => {
              resolve(reader.result as string);
            };
            reader.readAsDataURL(file);
          });
          
          // 顺序上传文件到OSS
          const fileName = await handleFileUpload(file, currentOssConfig);
          
          if (fileName) {
            // 上传文件信息到服务器
            const media = await uploadFileInfo(file, fileName);
            if(media !== null) {
              newImages.push({ 
                file, 
                preview, 
                url: fileName,
                type: file.type,
                id: media.id || "",
                size: media.size,
                width: media.width,
                height: media.height,
                deleted: false,
              });
            }

          } else {
            console.error(`文件 ${file.name} 上传失败`);
            // 即使某个文件上传失败，也继续处理下一个文件

          }
        }
        setMediaItems(prev => [...prev, ...newImages]);

      } catch (error) {
        console.error('获取OSS配置或多图上传失败:', error);
        alert('上传失败，请稍后再试');
      } finally {
        setIsUploading(false); // 上传完成，允许添加新文件
        setUploadProgress(0); // 重置上传进度
      }
    }
  };

  const removeImage = (index: number) => {
    setMediaItems(prev => {
      const newItems = [...prev];
      const item = newItems[index];
      
      // 如果是编辑模式且该项有ID（来自服务器），则标记为删除
      if (isEdit && item.id) {
        newItems[index] = { ...item, deleted: true };
        console.log('标记媒体项为已删除:', item.id);
        return newItems;
      } else {
        // 如果是新添加的项目（没有ID），直接从数组中移除
        return newItems.filter((_, i) => i !== index);
      }
    });
  };

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;

    if (active.id !== over?.id) {
      setMediaItems((items) => {
        // 只在未删除的项目中进行拖拽排序
        const activeItems = items.filter(item => !item.deleted);
        const oldIndex = activeItems.findIndex((item, index) => index.toString() === active.id);
        const newIndex = activeItems.findIndex((item, index) => index.toString() === over?.id);
        
        if (oldIndex !== -1 && newIndex !== -1) {
          const reorderedActiveItems = arrayMove(activeItems, oldIndex, newIndex);
          // 将重新排序的活动项目与删除的项目合并
          const deletedItems = items.filter(item => item.deleted);
          return [...reorderedActiveItems, ...deletedItems];
        }
        
        return items;
      });
    }
  };

  const reorderImages = (dragIndex: number, hoverIndex: number) => {
    const draggedImage = mediaItems[dragIndex];
    const newItems = [...mediaItems];
    newItems.splice(dragIndex, 1);
    newItems.splice(hoverIndex, 0, draggedImage);
    setMediaItems(newItems);
  };

  // 可拖拽的图片项组件
  const SortableImageItem = ({ image, index, onRemove, onSetCover }: {
    image: { file?: File; preview: string; url: string; type: string; size: number; width?: number; height?: number; id?: string };
    index: number;
    onRemove: () => void;
    onSetCover: () => void;
  }) => {
    const {
      attributes,
      listeners,
      setNodeRef,
      transform,
      transition,
      isDragging,
    } = useSortable({ id: index.toString() });
  
    const style = {
      transform: CSS.Transform.toString(transform),
      transition,
      opacity: isDragging ? 0.5 : 1,
    };

    return (
      <div
        ref={setNodeRef}
        style={style}
        {...attributes}
        className="relative group"
      >
      <div
        className="cursor-pointer"
        onClick={onSetCover}
      >
        <img
          src={image.preview}
          alt={`图片 ${index + 1}`}
          {...listeners}

          className="w-full h-32 object-cover rounded-md"
        />
        <button
          type="button"
          onClick={(e) => {
            e.stopPropagation();
            console.log('删除按钮被点击');
            onRemove();
          }}
          className="absolute top-2 right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity z-10"
        >
          <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
        {/* <div className="absolute bottom-2 left-2 bg-black bg-opacity-50 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity">
          点击设为封面
        </div> */}

      {/* <div
        className="absolute top-2 left-2 bg-blue-500 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity cursor-move z-10"
      >
        拖拽排序
      </div> */}

        </div>
      </div>
    );
  };

  return (
    <div className="space-y-6">
      <div className="bg-white rounded-lg shadow p-6">
        <div className="bg-white shadow-sm rounded-lg p-6">
          <h1 className="text-2xl font-bold text-gray-900 mb-6">发布内容</h1>
          
          <form onSubmit={handleSubmit} className="space-y-6">
            
            {/* <div className="space-y-2">
              <Label>封面图片</Label>
              <div 
                onClick={handleImageClick} 
                className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center cursor-pointer hover:border-gray-400 transition-colors"
              >
                {imagePreview ? (
                  <div className="relative">
                    <img 
                      src={imagePreview} 
                      alt="预览" 
                      className="mx-auto max-h-[200px] rounded-md" 
                    />
                    <p className="mt-2 text-sm text-gray-500">点击下面的图更换封面</p>
                  </div>
                ) : (
                  <div className="py-12">
                    <svg 
                      className="mx-auto h-12 w-12 text-gray-400" 
                      fill="none" 
                      viewBox="0 0 24 24" 
                      stroke="currentColor" 
                      aria-hidden="true"
                    >
                      <path 
                        strokeLinecap="round" 
                        strokeLinejoin="round" 
                        strokeWidth={2} 
                        d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" 
                      />
                    </svg>
                    <p className="mt-2 text-sm text-gray-500">点击上传图片</p>
                    <p className="mt-1 text-xs text-gray-400">支持 JPG, PNG, WEBP 格式</p>
                  </div>
                )}
                 <input 
                  type="file" 
                  ref={fileInputRef} 
                  onChange={handleImageChange} 
                  accept="image/*" 
                  className="hidden" 
              </div>
            </div> */}

            <div className="space-y-2">
              <Label>图片编辑器</Label>
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-4">
                {uploadProgress > 0 && uploadProgress < 100 && (
                  <div className="mb-4 space-y-2">
                    <div className="flex justify-between text-sm text-gray-600">
                      <span>上传进度</span>
                      <span>{uploadProgress}%</span>
                    </div>
                    <Progress value={uploadProgress} className="w-full" />
                  </div>
                )}
                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mb-4">
                  <DndContext
                    sensors={sensors}
                    collisionDetection={closestCenter}
                    onDragEnd={handleDragEnd}
                  >
                    <SortableContext
                      items={mediaItems.filter(item => !item.deleted).map((_, index) => index.toString())}
                      strategy={rectSortingStrategy}
                    >
                      {mediaItems.filter(item => !item.deleted).map((image, originalIndex) => {
                        const actualIndex = mediaItems.indexOf(image);
                        return (
                          <SortableImageItem
                            key={actualIndex}
                            image={image}
                            index={actualIndex}
                            onRemove={() => removeImage(actualIndex)}
                            onSetCover={() => {
                              setImagePreview(image.preview);
                              setCoverImage(image.file as File);
                            }}
                          />
                        );
                      })}
                    </SortableContext>
                  </DndContext>
                  <label className={`border-2 border-dashed rounded-md flex flex-col items-center justify-center h-32 transition-colors ${
                    isUploading 
                      ? 'border-gray-200 bg-gray-50 cursor-not-allowed' 
                      : 'border-gray-300 cursor-pointer hover:border-gray-400'
                  }`}>
                    {isUploading ? (
                      <>
                        <svg className="h-8 w-8 text-gray-300 animate-spin" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        <span className="mt-2 text-sm text-gray-400">上传中...</span>
                      </>
                    ) : (
                      <>
                        <svg className="h-8 w-8 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                        </svg>
                        <span className="mt-2 text-sm text-gray-500">添加图片</span>
                      </>
                    )}
                    <input 
                      type="file" 
                      onChange={handleMultiImageChange} 
                      accept="image/*" 
                      className="hidden" 
                      multiple
                      disabled={isUploading}
                    />
                  </label>
                </div>
                <p className="text-xs text-gray-400 text-center">支持拖拽排序，点击图片可删除或设为封面</p>
              </div>
            </div>
            
            {/* 标题输入区域 */}
            <div className="space-y-2">
              <Label htmlFor="title" className="text-gray-700 font-medium">标题</Label>
              <Input 
                id="title" 
                value={title} 
                onChange={(e) => setTitle(e.target.value)} 
                placeholder="请输入标题" 
                className="focus-visible:ring-2 focus-visible:ring-blue-500"
                required 
              />
            </div>
            
            {/* 正文内容区域 */}
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <Label htmlFor="body" className="text-gray-700 font-medium">正文内容</Label>
                <div className="flex items-center gap-2">
                  <span className={`text-sm transition-colors ${
                    charCount >= maxChars * 0.9 
                      ? charCount >= maxChars 
                        ? 'text-red-500 font-medium' 
                        : 'text-orange-500'
                      : 'text-gray-500'
                  }`}>
                    {charCount} / {maxChars}
                  </span>
                  {charCount >= maxChars && (
                    <span className="text-xs text-red-500 bg-red-50 px-2 py-1 rounded">
                      已达上限
                    </span>
                  )}
                </div>
              </div>
              
              <div className="relative border border-gray-300 rounded-lg overflow-hidden focus-within:ring-2 focus-within:ring-blue-500 focus-within:border-blue-500 transition-all">
                <Textarea 
                  id="body" 
                  value={body} 
                  onChange={(e) => {
                    const newValue = e.target.value;
                    if (newValue.length <= maxChars) {
                      setBody(newValue);
                    }
                  }} 
                  placeholder="填写正文内容，真诚有价值的分享予人温暖" 
                  className="min-h-[200px] border-0 focus-visible:ring-0 resize-none px-4 py-3 text-gray-800 placeholder:text-gray-400" 
                  required 
                  maxLength={maxChars}
                />
                
                {/* 底部状态栏 */}
                <div className="bg-gray-50 px-4 py-2 border-t border-gray-200">
                  <div className="flex justify-between items-center">
                    <span className="text-xs text-gray-400">
                      支持换行和基本格式
                    </span>
                    <div className="flex items-center gap-2">
                      {charCount >= maxChars && (
                        <span className="text-xs text-red-500 animate-pulse">
                          已达到字数上限
                        </span>
                      )}
                      {charCount > 0 && charCount < maxChars && (
                        <span className="text-xs text-green-600">
                          还可输入 {maxChars - charCount} 字
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            



            <div className="space-y-2">
              <div className="flex items-center gap-4">
                <div>
                  <Label htmlFor="visibility">可见范围</Label>
                </div>
                <div>
                  <Select value={visibility} onValueChange={setVisibility}>
                    <SelectTrigger className="w-[200px]">
                      <SelectValue placeholder="选择可见范围" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="private">仅支持者可见</SelectItem>
                      <SelectItem value="public">公开可见</SelectItem>
                      <SelectItem value="Purchase">仅购买</SelectItem>
                      <SelectItem value="Paid">所选方案等级</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
            {showPriceInput && (
              <div className="space-y-2">
                <Label htmlFor="price">价格</Label>
                <div className="flex items-center gap-2">
                  <Input
                    id="price"
                    type="number"
                    min="0"
                    step="0.01"
                    value={price}
                    onChange={(e) => setPrice(Number(e.target.value))}
                    placeholder="0.00"
                  />
                  <span className="w-[50px]">
                  金币
                  </span>
                  
                </div>
              </div>
            )}
            <div></div>
            {visibility === 'Paid' && (
              <MembershipSelector
                membershipTiers={membershipTiers}
                selectedTiers={selectedMembershipTiers}
                onSelectionChange={handleMembershipSelectionChange}
              />
            )}
            <div className="pt-4">
              {id != "0" && (
                <Button type="submit" className="w-full sm:w-auto"
                  onClick={handleSubmit}
                >
                  编辑完成
                </Button>
              )}
              {id == "0" && (
                <Button type="submit" className="w-full sm:w-auto"
                  onClick={handleSubmit}
                >
                  发布内容
                </Button>
              )}  
              
              
              
              {sendMessage && <MessageAlert message={sendMessage} />}
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Publish;